package com.tp2.etna.distribucion2.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.tp2.etna.distribucion2.modelo.BackOrder;

@Repository
public class BackOrderDAOImpl implements BackOrderDAO {

	@Autowired
    private DataSource dataSource;
	
	@Override
	public void insert(BackOrder backorder) {
		String query = "insert into Backorder (fechaEmision,idEntrega) values (curdate(),?)";
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try{
            con = dataSource.getConnection();
            ps = con.prepareStatement(query);
            ps.setInt(1, backorder.getEntrega().getCodigo());
            int out = ps.executeUpdate();
            if(out !=0){
            	ps.close();
            	query = " select max(codigo) as codigoBackOrder from Backorder";
            	ps = con.prepareStatement(query);
            	rs = ps.executeQuery();
            	if(rs.next()){
            		backorder.setCodigo(rs.getInt("codigoBackOrder"));
            	}
            }
        }catch(SQLException e){
            e.printStackTrace();
        }finally{
            try {
            	if(rs!=null)
            		rs.close();
                ps.close();
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
	}

}
